import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { Table, Button, Tag, notification } from 'antd'
import { NavLink } from 'dva/router'

export default function Audit() {
    const [dataSource, setdataSource] = useState([])
    const { roleId, username, region } = JSON.parse(localStorage.getItem('token'))

    // 审核列表只能看到'审核中', '已通过', '未通过',  看不到未审核:在草稿箱
    const auditList = ['未审核', '审核中', '已通过', '未通过']
    // 审核列表只能看到 '未发布'（未通过+未审核+审核中）, '待发布'（已通过）
    // const publishList = ['未发布', '待发布', '已发布', '已下线']
    useEffect(() => {
        const roleObj = {
            '1': 'superadmin',
            '2': 'admin',
            '3': 'editor'
        }
        axios(`/news?auditState=1&_expand=category`).then(res => {
            var list = res.data
            setdataSource(roleObj[roleId] === 'superadmin' ? list : [
                // 接收自身数据
                ...list.filter(item => item.author === username),
                // 以及和自身同地区且低一级别的数据
                ...list.filter(item => item.region === region && roleObj[item.roleId] === 'editor')
            ])
        })
    }, [username, roleId, region])

    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'label',
            render: (label, item) => {
                return <NavLink to={`/news-manage/preview/${item.id}`}>{label}</NavLink>
            },
        },
        {
            title: '作者',
            dataIndex: 'author',

        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category) => {
                return <div>{category.label}</div>
            },
        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            render: (auditState) => {
                const colorList = ['', 'orange', 'green', 'red']
                return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
            },
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button type='primary' onClick={() => handleAudit(item,2,1)}>通过</Button>
                    <Button danger onClick={() => handleAudit(item,3,0)}>驳回</Button>
                </div>
            },
        },
    ];
    const handleAudit = (item, auditState, publishState)=>{
        setdataSource(dataSource.filter(items => items.id !== item.id))
        axios.patch(`/news/${item.id}`, {
            auditState: auditState,
            publishState: publishState,
        }).then(res => {
            notification.info({
                message: `通知`,
                description:
                    `${auditList[auditState]},您可以到[审核管理/审核列表]中查看您的新闻`,
                placement: 'bottomRight',
            });
        })
    }
    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 5,
            }} rowKey={item => item.id} />

        </div>
    )
}
